package com.atguigu.gmall.pms.config;

import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;

/**
 * @author Jia Fa
 * @create 2021-12-09 14:26
 */
@Configuration
@Slf4j
public class RabbitConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @PostConstruct  // bean创建最后阶段执行  构造器
    public void init(){
        // 生产者确认机制 消息到交换机
        this.rabbitTemplate.setConfirmCallback((@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause)->{
            if (!ack){
                log.error("消息发送到交换机失败,失败原因为->{}", cause);
            }
        });

        // 生产者确认机制  消息从交换机到队列  未执行则发送成功
        this.rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey)->{


            log.error("消息从交换机到队列失败,交换机为-->{},路由键为-->{},消息为-->{}",exchange,routingKey,new String(message.getBody()));
        });
    }
}
